package com.wechat.backend.controller;

import com.wechat.backend.entity.User;
import com.wechat.backend.repository.UserRepository;
import com.wechat.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    public static class RegisterRequest {
        public String username;
        public String password;
        public String nickname;
    }

    @PostMapping("/register")
    public User register(@RequestBody RegisterRequest req) {
        return userService.register(req.username, req.password, req.nickname);
    }

    public static class LoginRequest {
        public String username;
        public String password;
    }

@PostMapping("/login")
public Map<String, Object> login(@RequestBody LoginRequest req) {
    Map<String, Object> result = new HashMap<>();
    User user = userService.login(req.username, req.password);
    if (user != null) {
        result.put("success", true);
        result.put("message", "登录成功");
        result.put("user", user);
    } else {
        result.put("success", false);
        result.put("message", "用户名或密码错误");
    }
    return result;
}

    @GetMapping("/search")
    public List<User> searchUser(@RequestParam String keyword) {
        // 支持按用户名或昵称模糊查找
        return userService.findByUsernameContainingOrNicknameContaining(keyword, keyword);
    }

    // 查询单个用户信息
    @GetMapping("/info")
    public User getUserInfo(@RequestParam Integer userId) {
        User user = userRepository.findById(userId);
        return user != null ? user : null;
    }
} 